package com.bang.study.query;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @ClassName: FullTextSearchByBrand
 * @author: BANG
 * @Date: 2020/01/14 09:20
 * @Version: 1.0
 * @Modified By:
 * @Desc: TODO
 */
public class FullTextSearchByBrand {

    public static void main(String[] args) throws UnknownHostException {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();

        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

        //matchQuery
        SearchResponse searchResponse = client.prepareSearch("car_shop").setTypes("cars")
                .setQuery(QueryBuilders.matchQuery("brand", "宝马"))
                .get();
        for (SearchHit searchHitFields : searchResponse.getHits().getHits()) {
            System.err.println(searchHitFields.getSourceAsString());
        }
        System.err.println("=======================matchQuery=============================");
        //multiMatchQuery
        searchResponse = client.prepareSearch("car_shop").setTypes("cars")
                .setQuery(QueryBuilders.multiMatchQuery("宝马", "brand", "name"))
                .get();
        for (SearchHit searchHitFields : searchResponse.getHits().getHits()) {
            System.err.println(searchHitFields.getSourceAsString());
        }
        System.err.println("=======================multiMatchQuery=============================");

        //termQuery
        searchResponse = client.prepareSearch("car_shop").setTypes("cars")
                .setQuery(QueryBuilders.termQuery("name.raw", "宝马320"))
                .get();
        for (SearchHit searchHitFields : searchResponse.getHits().getHits()) {
            System.err.println(searchHitFields.getSourceAsString());
        }
        System.err.println("=======================termQuery=============================");

        //prefixQuery
        searchResponse = client.prepareSearch("car_shop").setTypes("cars")
                .setQuery(QueryBuilders.prefixQuery("name", "宝"))
                .get();
        for (SearchHit searchHitFields : searchResponse.getHits().getHits()) {
            System.err.println(searchHitFields.getSourceAsString());
        }
        System.err.println("========================prefixQuery============================");

        client.close();
    }
}
